/*
 * 文件名：CitySurveyController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：chenhan
 * 修改时间：2020年1月6日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.sg.web;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import top.infopub.generic.GenericController;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.sg.service.CitySurveyAttService;
import top.infopub.mgr.sg.service.CitySurveyLogService;
import top.infopub.mgr.sg.service.CitySurveyService;
import top.infopub.mgr.sys.service.LocationAreaDataService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.sg.CitySurvey;
import top.infopub.model.sg.CitySurveyAtt;
import top.infopub.model.sg.CitySurveyLog;
import top.infopub.model.sys.Area;
import top.infopub.model.sys.City;
import top.infopub.model.sys.Province;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 城市调研信息
 *
 * @author chenhan
 * @version 2020年1月6日
 * @see CitySurveyController
 * @since
 */
@Controller
@RequestMapping("/citySurvey")
public class CitySurveyController extends GenericController {

    @Autowired
    private CitySurveyService citySurveyService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private LocationAreaDataService locationAreaDataService;

    @Autowired
    private CitySurveyLogService citySurveyLogService;

    @Autowired
    private CitySurveyAttService citySurveyAttService;

    /**
     * 编号类型
     */
    private static final String PARAMGROUP_CODE = "sg_city_survey";

    /**
     * 城市管理列表
     *
     * @return
     * @see
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        Set<Province> provinces = locationAreaDataService.selectProvincesAndsort();
        request.setAttribute("provinces", provinces);
        return "sg/lay-citySurvey-list";
    }

    /**
     * 城市调研信息数据查询-list查询方法
     * @return
     */
    @RequestMapping("/queryCitySurvey")
    @ResponseBody
    public RspVo<CitySurvey> queryCitySurvey(CitySurvey citySurvey, ParamPage paramPage) {
        Page<CitySurvey> page = new Page<CitySurvey>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = citySurveyService.selectPageByDomainWhere(page, citySurvey);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 查询附件
     * @param request
     * @param id
     * @return
     * @see
     */
    @RequestMapping("/queryAttsById")
    public @ResponseBody Map<String, Object> queryAttsById(HttpServletRequest request, String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            CitySurveyAtt where = new CitySurveyAtt();
            where.setSurveyId(id);
            List<CitySurveyAtt> atts = citySurveyAttService.selectByEntityWhere(where);
            map.put("atts", atts);
        }
        catch (Exception e) {
            log.error("", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据id查询保存记录
     * @param id 城市调研对象的主键
     * @return
     * @see
     */
    @RequestMapping("/selectLogsById")
    @ResponseBody
    public RspVo<CitySurveyLog> selectLogsById(String id) {
        CitySurveyLog where = new CitySurveyLog();
        where.setSurveyId(id);
        List<CitySurveyLog> logs = citySurveyLogService.selectByEntityWhere(where);
        return RspVo.getSuccessResponse(0, logs);
    }

    @RequestMapping("/selectCitySurveyById")
    @ResponseBody
    public RspVo<CitySurvey> selectCitySurveyById(String id) {
        CitySurvey citySurvey = citySurveyService.selectByPrimaryKey(id);
        return RspVo.getSuccessResponse(0, citySurvey);
    }

    /**
     * 新增城市调研信息
     * @param citySurvey
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/save")
    public @ResponseBody RspVo<CitySurvey> save(HttpServletRequest request, CitySurvey citySurvey) {
        // 必要信息判断
        if (StringUtils.isEmpty(citySurvey.getRefProvinceId())
            || StringUtils.isEmpty(citySurvey.getRefCityId())
            || StringUtils.isEmpty(citySurvey.getCityLevel())) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
        }
        // 添加城市编号
        citySurvey.setCityCode(codeGeneratorConfigService.generatorCode(PARAMGROUP_CODE));
        // 设置添加时间和数据状态
        citySurvey.setAddTime(new Date());
        citySurvey.setState(1);
        //添加人（拿到当前登录用户）
        citySurvey.setAddBy(SessionUserUtils.getSessionUserId());
        //修改人
        citySurvey.setUptBy(SessionUserUtils.getSessionUserId());
        citySurvey.setUptTime(new Date());
        // 拼接城市名
        String proName = locationAreaDataService.selectProvinceNameById(citySurvey.getRefProvinceId());
        String cName = locationAreaDataService.selectCityNameById(citySurvey.getRefCityId());
        String areaName = "";
        if (StringUtils.isNotBlank(citySurvey.getRefAreaId())) {
            areaName = locationAreaDataService.selectAreaNameById(citySurvey.getRefAreaId());
        }
        String cityName = proName + cName + areaName;
        // 拿到上传的文件
        String[] fileAtt = request.getParameterValues("fileAtt");
        citySurvey.setCityName(cityName);
        // 判断城市是否存在
        if (checkNameIsExist(cityName)) {
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("城市【" + cityName + "】已经存在~");
        }
        citySurvey.setId(IdFactory.getUUIDUpper());
        //获取当前登陆人信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
        * 上传的文件记录加入集合
        */
        List<CitySurveyAtt> fileAtts = new ArrayList<CitySurveyAtt>();

        //城市调研附件
        if (fileAtt != null) {
            for (String file : fileAtt) {
                CitySurveyAtt preProjectAtt = createFileAtt(vo, citySurvey.getId(), file);
                fileAtts.add(preProjectAtt);
            }
        }
        // 将调研信息和附件数据插入数据库
        citySurveyService.addCitySurvey(citySurvey, fileAtts);
        return RspVo.getSuccessResponse(citySurvey);
    }


    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "citySurveyAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传城市调研附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 编辑修改
     * @param request
     * @param citySurvey
     * @return
     * @see
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/editCitySurvey")
    public @ResponseBody RspVo<CitySurvey> editCitySurvey(HttpServletRequest request,
                                                          CitySurvey citySurvey) {
        String proName = locationAreaDataService.selectProvinceNameById(citySurvey.getRefProvinceId());
        String cName = locationAreaDataService.selectCityNameById(citySurvey.getRefCityId());
        String areaName = "";
        if (StringUtils.isNotBlank(citySurvey.getRefAreaId())) {
            areaName = locationAreaDataService.selectAreaNameById(citySurvey.getRefAreaId());
        }
        String cityName = proName + cName + areaName;
        citySurvey.setCityName(cityName);
        // 验证修改的城市名存不存在
        if (checkNewCityNameIsExist(citySurvey.getCityName(), citySurvey.getId())) {
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("城市【" + citySurvey.getCityName()
                                                            + "】已经存在~");
        }
        citySurvey.setUptBy(SessionUserUtils.getSessionUserId());
        citySurvey.setUptTime(DateUtils.getCurrentDateTime());
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String[] fileAtt_edit = request.getParameterValues("fileAtt"); //编辑之后的附件集合
        List<CitySurveyAtt> afterAtts = new ArrayList<CitySurveyAtt>(); //编辑后的附件对象集合
        // 编辑后的城市调研附件
        if (fileAtt_edit != null) {
            for (String file : fileAtt_edit) {
                CitySurveyAtt preProjectAtt = createFileAtt(vo, citySurvey.getId(), file);
                afterAtts.add(preProjectAtt);
            }
        }
        // 修改数据库
        citySurveyService.updtCitySurvey(citySurvey, afterAtts);
        if (StringUtils.isEmpty(citySurvey.getId())) {
            LogUtil.bizLog(LogModelType.OTHER, AcctionType.UPDATE,
                "修改城市调研 - 城市调研Id:" + citySurvey.getId(), null);
        }
        return RspVo.getSuccessResponse(citySurvey);
    }

    /**
     * * 根据省份查找城市
     */
    @RequestMapping("/getCityByPro")
    @ResponseBody
    public Map<String, Object> getCityByPro(String proId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Set<City> citys = locationAreaDataService.selectCitysByProvIdAndSort(proId);
            map.put("citys", citys);
        }
        catch (Exception e) {
            log.error("根据省份查找城市异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据市查找县
     * @param cityId
     * @return
     */

    @RequestMapping("/getAreaByCity")
    @ResponseBody
    public Map<String, Object> getAreaByCity(String cityId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Set<Area> areas = locationAreaDataService.selectAreasByCityIdAndSort(cityId);
            map.put("areas", areas);
        }
        catch (Exception e) {
            log.error("根据城市查找区县异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    private CitySurveyAtt createFileAtt(AuthorizationVO vo, String citySurveyId, String file) {
        // 资料信息数组
        String[] fileAttStr = file.split("\\|");
        CitySurveyAtt fileAtt = new CitySurveyAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setSurveyId(citySurveyId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 存在返回true
     * @param cityName
     * @return
     * @see
     */
    private boolean checkNameIsExist(String cityName) {
        if (StringUtils.isBlank(cityName)) {
            return false;
        }
        CitySurvey t = new CitySurvey();
        t.setCityName(cityName);
        List<CitySurvey> selectByEntityWhere = citySurveyService.selectByEntityWhere(t);
        return selectByEntityWhere.size() > 0;
    }

    /**
     * 存在返回true
     * @param cityName
     * @param id
     * @return
     * @see
     */
    private boolean checkNewCityNameIsExist(String cityName, String id) {
        if (StringUtils.isBlank(cityName)) {
            return false;
        }
        return citySurveyService.selectByCityNameAndId(cityName, id);
    }

}
